/*
* Copyright (c) 2016 . All Rights Reserved.
*/
package com.cgmnx.admin.web.controller.rbac;

import com.cgmnx.admin.biz.rbac.RoleBiz;
import com.cgmnx.admin.common.bean.ApiRes;
import com.cgmnx.admin.common.bean.Limiter;
import com.cgmnx.admin.common.bean.UserContext;
import com.cgmnx.admin.common.constants.WebConstant;
import com.cgmnx.admin.common.enums.ValidEnumType;
import com.cgmnx.admin.common.exception.Preconditions;
import com.cgmnx.admin.common.util.WebUtils;
import com.cgmnx.admin.dao.entity.rbac.RoleEntity;
import com.cgmnx.admin.dao.entity.rbac.RoleUserRelationEntity;
import com.cgmnx.admin.service.rbac.RoleUserRelationService;
import com.cgmnx.admin.web.converter.entity.RoleEntityConverter;
import com.cgmnx.admin.web.converter.vm.RoleVmConverter;
import com.cgmnx.admin.web.model.param.RoleAllocationParam;
import com.cgmnx.admin.web.model.param.RoleBindingUserParam;
import com.cgmnx.admin.web.model.param.RoleParam;
import com.cgmnx.admin.web.model.vm.RoleVm;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author: created  Date: 16/12/13 Time: 下午6:06
 * @version: 1.0
 */
@Slf4j
@Controller
public class RoleController {

    @Autowired
    private RoleBiz roleBiz;

    @Autowired
    private RoleUserRelationService roleUserRelationService;

    @Autowired
    private RoleEntityConverter roleEntityConverter;

    @Autowired
    private RoleVmConverter roleVmConverter;

    @RequestMapping("/cgmnx/rbac/role/save.json")
    @ResponseBody
    public ApiRes save(@Validated @RequestBody RoleParam roleParam, BindingResult result) {

        if (result.hasErrors()) {
            return ApiRes.returnFail(WebUtils.resolveBindingResult(result));
        }

        RoleEntity convert = roleEntityConverter.convert(roleParam);
        convert.setValidStatus(ValidEnumType.VALID);
        roleBiz.save(convert);
        return ApiRes.returnSuccess(convert.getId());

    }

    @RequestMapping("/cgmnx/rbac/role/update.json")
    @ResponseBody
    public ApiRes update(@Validated @RequestBody RoleParam roleParam, BindingResult result) {

        if (result.hasErrors()) {
            return ApiRes.returnFail(WebUtils.resolveBindingResult(result));
        }

        RoleEntity convert = roleEntityConverter.convert(roleParam);
        try {
            roleBiz.update(convert);
        } catch (Exception e) {
            return ApiRes.returnFail("角色已经存在");
        }
        return ApiRes.returnSuccess();


    }

    @RequestMapping("/cgmnx/rbac/role/disable.json")
    @ResponseBody
    public ApiRes disable(@RequestParam("id") Integer id) {

        List<RoleUserRelationEntity> roleUserRelationEntities = roleUserRelationService.queryByRoleId(id);

        Preconditions.checkArgument(CollectionUtils.isEmpty(roleUserRelationEntities), "该角色下面存在用户,不能删除");

        roleBiz.updateInValidStatus(Lists.<Integer>newArrayList(id));

        return ApiRes.returnSuccess("更新成功");

    }

    @RequestMapping("/cgmnx/rbac/role/enable.json")
    @ResponseBody
    public ApiRes enable(@RequestParam("id") Integer id) {

        roleBiz.updateValidStatus(Lists.<Integer>newArrayList(id));

        return ApiRes.returnSuccess("更新成功");

    }

    @RequestMapping("/cgmnx/rbac/role/allocation.json")
    @ResponseBody
    public ApiRes allocation(@Validated @RequestBody RoleAllocationParam param) {

        roleBiz.allocationResource(param.getRoleId(), param.getUriIds(), UserContext.getUserInfo().getUserId());

        return ApiRes.returnSuccess("更新成功");

    }

    @RequestMapping("/cgmnx/rbac/role/bindingUser.json")
    @ResponseBody
    public ApiRes bindingUser(@Validated @RequestBody RoleBindingUserParam param) {

        roleBiz.bindingUser(param.getRoleId(), param.getUserIds(), UserContext.getUserInfo().getUserId());

        return ApiRes.returnSuccess("更新成功");

    }

    @RequestMapping("/cgmnx/rbac/role/query.json")
    @ResponseBody
    public ApiRes query(@RequestParam("id") Integer id) {

        RoleEntity query = roleBiz.query(id);

        return ApiRes.returnSuccess(roleVmConverter.convert(query));

    }

    @RequestMapping("/cgmnx/rbac/role/queryPage.json")
    @ResponseBody
    public ApiRes queryPage(@RequestParam(value = "roleName", required = false) String roleName,
                            @RequestParam(value = "offset", required = false, defaultValue = WebConstant.DEFAULT_PAGE_OFFSET) Integer offset,
                            @RequestParam(value = "pageSize", required = false, defaultValue = WebConstant.DEFAULT_PAGE_SIZE) Integer pageSize) {

        Integer count = roleBiz.count(roleName);
        if (count == null || count <= 0) {
            return ApiRes.emptyList();
        }

        List<RoleEntity> roleEntities = roleBiz.queryPage(roleName, Limiter.create(offset, pageSize));

        List<RoleVm> roleVms = roleVmConverter.convert(roleEntities);

        return ApiRes.list(roleVms, count);

    }

    @RequestMapping("/cgmnx/rbac/role/relationUser.json")
    @ResponseBody
    public ApiRes relationUser(@RequestParam("id") Integer id,
                               @RequestParam(value = "offset", required = false, defaultValue = WebConstant.DEFAULT_PAGE_OFFSET) Integer offset,
                               @RequestParam(value = "pageSize", required = false, defaultValue = WebConstant.DEFAULT_PAGE_SIZE) Integer pageSize) {

        Integer count = roleBiz.countRelationUser(id);
        if (count == null || count <= 0) {
            return ApiRes.emptyList();
        }

        List<RoleEntity> roleEntities = roleBiz.queryRelationUserPage(id, Limiter.create(offset, pageSize));
        return ApiRes.list(roleEntities, count);

    }


}